<?php

namespace app\service;

use app\core\exception\BusinessException;
use app\core\Service;
use app\model\Settings;
use think\facade\Db;

/**
 * @extends Service<SettingsService>
 */
class SettingsService extends Service
{
    public function getList($page, $limit, $searchQuery = null)
    {
        $w = [];
        if (!empty($searchQuery['product_name'])) {
            $w[] = ['product_name', 'like', "%" . $searchQuery['product_name'] . "%"];
        }
        if (!empty($searchQuery['product_status']) && $searchQuery['product_status'] != '') {
            $w[] = ['product_status', '=', $searchQuery['product_status']];
        }
        $map = Settings::where($w)->page($page, $limit);
        return [
            'total' => $map->count(),
            'list' => $map->select(),
        ];
    }

    public function getInfo($type)
    {
        $info = Settings::where(['type' => $type])->find();
        if (!$info) {
            throw new BusinessException('数据不存在');
        }
        return $info->toArray();
    }


    public function saveCharge($data, $type)
    {
        Db::startTrans();
        try {
            $info = Settings::where('type', $type)->find();
            if (empty($info)) {
                Settings::create([
                    'type' => $type,
                    'charge' => !empty($data['charge']) ? $data['charge'] : 0,
                ]);
            }else{
                $info->save(['charge' => $data['charge']]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new BusinessException($e->getMessage());
        }

        return true;
    }

    public function save($data, $id)
    {
        Db::startTrans();
        try {
            if (empty($id)) {
                Settings::create([
                    'phone' => !empty($data['phone']) ? $data['phone'] : '',
                    'image' => !empty($data['image']) ? $data['image'] : '',
                    'type' => !empty($data['type']) ? $data['type'] : 0,
                    'charge' => !empty($data['charge']) ? $data['charge'] : 0,
                ]);
            } else {
                $info = Settings::where('id', $id)->find();
                if (empty($info)) {
                    throw new \Exception('数据不存在');
                }
                $goods = [];
                if (!empty($data['phone'])) {
                    $goods['phone'] = $data['phone'];
                }
                if (!empty($data['image'])) {
                    $goods['image'] = $data['image'];
                }
                if (!empty($data['type'])) {
                    $goods['type'] = $data['type'];
                }
                $info->save($goods);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new BusinessException($e->getMessage());
        }

        return true;
    }


}